package context.dao;

import context.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ForwardRepository {
    private final String SELECT_BY_ID = "select * from forward where userid=?";
    private final String INSERT_DYNAMIC = "insert into forward(dynamic_id,forwarddate) values(?,?)";

    private JdbcTemplate jdbcTemplate;

    @Autowired          //自动装配
    public ForwardRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    private User mapRow(ResultSet resultSet, int i) throws SQLException {
        User result = new User();
        result.setId(resultSet.getLong("dynamic_id"));
        result.setId(resultSet.getLong("forwarddate"));
        return result;
    }

    //增
    public int insertFowardInformation(final String dynamic_id, final String forwarddate) {

        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(
                new PreparedStatementCreator() {
                    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
                        PreparedStatement ps = jdbcTemplate.getDataSource()
                                .getConnection().prepareStatement(INSERT_DYNAMIC, new String[]{"dynamic_id", "forwarddate"});
                        ps.setString(1, dynamic_id);
                        ps.setString(2, forwarddate);
                        return ps;
                    }
                }, keyHolder);
        System.out.println("自动插入id============================" + keyHolder.getKey().intValue());
        return keyHolder.getKey().intValue();
    }

    //删
    private static final String sql = "delete  from forward where userid = ?";

    public void delete(int userid) {
        Object[] obj = new Object[]{userid};
        int i = jdbcTemplate.update(sql, obj);

        if (i > 0) {
            System.out.println("删除成功");
        } else {
            System.out.println("删除失败");
        }
    }

    //查
    public User findUserByID(long id) {

        try {
            return jdbcTemplate.queryForObject(SELECT_BY_ID, this::mapRow, id);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }

    }
}
